import CustomerValueType from '@fc-rc/customer-value-type';
import type {
  ProDescriptionsItemProps,
  ProDescriptionsProps,
  ProFormColumnsType,
  
} from '@ant-design/pro-components';
import { ProDescriptions } from '@ant-design/pro-components';
import { Button, Modal, Spin, Space, Divider } from 'antd';
import type { Dispatch, ReactNode, SetStateAction } from 'react';
import { useCallback, useEffect } from 'react';
import React, { useState } from 'react';
import type { FormSchema,FormFieldType } from "@ant-design/pro-components/node_modules/@ant-design/pro-form/lib/components/SchemaForm/typing";

/*
 * @Author: zoufengfan
 * @Date: 2022-08-17 16:05:26
 * @LastEditTime: 2022-08-22 10:23:12
 * @LastEditors: zoufengfan
 */
export type Props<Item> = {
  title: string;
  trigger?: (() => JSX.Element) | JSX.Element;
  // loading: boolean;
  request: () => Promise<Item>;
  /** colSize: descriptionItem占的位置多少 colProps.span: formItem占的位置多少 */
  columns:
    | ProFormColumnsType<Item, 'text' | FormFieldType>[]
    | ((values: any) => ProFormColumnsType<Item, 'text' | FormFieldType>[]);
  proDescriptionsProps?: {
    <RecordType extends Record<string, any>, ValueType = 'text'>(
      props: ProDescriptionsProps<RecordType, ValueType>,
    ): JSX.Element;
    Item: React.FC<ProDescriptionsItemProps<Item, 'text'>>;
  };
  visible?: boolean;
  /**控制关闭 */
  visibleAction?: Dispatch<SetStateAction<boolean>>;
  /**当页面显示,不弹窗显示 */
  isPage?: boolean;
  footer?: JSX.Element;
};

function Detail<Item>(props: Props<Item>) {
  const {
    trigger,
    title,
    columns,
    request,
    proDescriptionsProps,
    visible,
    visibleAction,
    footer,
    isPage,
  } = props;
  const [_visible, set_visible] = useState(false);
  const [dataSource, setdataSource] = useState<Item>({} as Item);
  const [loading, setloading] = useState(true);
  const [cols, setcols] = useState<ProFormColumnsType<Item, 'text' | FormFieldType>[]>([]);

  // 请求详情
  useEffect(() => {
    if (isPage || (visibleAction ? visible : _visible)) {
      setloading(true);
      request()
        .then((res) => {
          console.log('dataSource ', res);

          setdataSource(res || ({} as Item));
        })
        .finally(() => {
          setloading(false);
        });
    }
  }, [request, _visible, visibleAction, visible, isPage]);

  // 对columns配置扁平化，主要处理valueType: 'dependency'|'group'的情况
  useEffect(() => {
    const stackArr = [...(typeof columns === 'function' ? columns(dataSource) : columns)].slice();

    const changeChildrenFunc = (data: ProFormColumnsType<Item, FormFieldType | 'text'>[]) => {
      for (let idx = 0; idx < data.length; idx++) {
        const item = data[idx];
        // 函数的情况下调用后继续递归处理
        if (typeof item.columns === 'function') {
          const _col = item.columns(dataSource);
          data.splice(idx, 1, ..._col);
          idx--;
          changeChildrenFunc(_col);
        }
        // 数组的情况下继续递归处理
        else if (Array.isArray(item.columns)) {
          changeChildrenFunc(item.columns);
        }
      }
    };

    changeChildrenFunc(stackArr);

    setcols(stackArr.filter((item) => !item.hideInDescriptions));
  }, [columns, dataSource]);

  return (
    <div>
      {isPage ? (
        <>
          <CustomerValueType>
            {cols.map((item, idx) => (
              <div key={idx}>
                <ProDescriptions
                  size="small"
                  dataSource={dataSource || ({} as Item)}
                  title={item.title as ReactNode}
                  columns={item.columns}
                  bordered
                  column={2}
                  {...proDescriptionsProps}
                />
                {idx !== cols.length - 1 && <Divider />}
              </div>
            ))}
          </CustomerValueType>
        </>
      ) : (
        <>
          <span onClick={() => (visibleAction ? visibleAction(true) : set_visible(true))}>
            {typeof trigger === 'function' ? trigger() : trigger}
          </span>
          <Modal
            title={title}
            width={1000}
            visible={visibleAction ? visible : _visible}
            onCancel={() => (visibleAction ? visibleAction(false) : set_visible(false))}
            footer={
              <Space>
                {footer}
                <Button onClick={() => (visibleAction ? visibleAction(false) : set_visible(false))}>
                  返回
                </Button>
              </Space>
            }
          >
            {/* <pre style={{ fontSize: '7px' }}>{JSON.stringify(cols, null, 2)}</pre> */}

            <Spin spinning={loading}>
              <CustomerValueType>
                {cols.map((item, idx) => (
                  <div key={idx}>
                    <ProDescriptions
                      className={item.className}
                      size="small"
                      dataSource={dataSource || ({} as Item)}
                      title={item.title as ReactNode}
                      columns={item.columns}
                      bordered
                      column={2}
                      {...proDescriptionsProps}
                    />
                    {idx !== cols.length - 1 && <Divider />}
                  </div>
                ))}
              </CustomerValueType>
            </Spin>
          </Modal>
        </>
      )}
    </div>
  );
}

export default Detail;
